<template>
  <div class="app-container usercenter">
    <div class="usercenter-header">
      <el-button type="primary" size="mini" @click="dialog.createUser = true">新建用户</el-button>
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="请输入邮箱搜索用户"
          clearable
          @keyup.enter.native="doSearch(false)"
          @clear="doSearch(true)" />
      </div>
    </div>
    <el-table
      :data="list"
      style="width: 100%">
      <el-table-column
        label="账号">
        <template slot-scope="scope">
          <div class="table-link">
            <span>{{ scope.row.account }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="用户名">
        <template slot-scope="scope">
          <div class="table-link">
            <span>{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="邮箱">
        <template slot-scope="scope">
          <div class="table-link">
            <span>{{ scope.row.email }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="size"
        label="操作"
        width="80">
        <template slot-scope="scope">
          <a class="table-action" @click="clickModifyUser(scope.row)">重置密码</a>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialog.createUser"
      :title="dialog.editUser ? '重置密码' : '新建用户'"
      width="500px"
      @close="resetForm('createPlateformUserForm')">
      <el-form ref="createPlateformUserForm" :model="createPlateformUserForm" :rules="rulesCreateUser" :label-width="dialog.editUser ? '120px' : '80px'">
        <el-form-item label="邮箱：" prop="email">
          <el-input :disabled="dialog.editUser" v-model="createPlateformUserForm.email" />
        </el-form-item>
        <el-form-item v-if="!dialog.editUser" label="用户名" prop="userName">
          <el-input v-model="createPlateformUserForm.userName" />
        </el-form-item>
        <el-form-item v-if="!dialog.editUser" label="密码：" prop="password" show-password>
          <el-input v-model="createPlateformUserForm.password" type="password" auto-complete="new-password" />
        </el-form-item>
        <el-form-item v-if="dialog.editUser" label="新密码：" prop="newPssword" show-password>
          <el-input v-model="createPlateformUserForm.newPssword" type="password" auto-complete="new-password" />
        </el-form-item>
        <el-form-item v-if="dialog.editUser" label="确认密码：" prop="confirmNewPssword" show-password>
          <el-input v-model="createPlateformUserForm.confirmNewPssword" type="password" auto-complete="new-password" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.createUser = false; dialog.editUser = false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('createPlateformUserForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { handlePlateFormUser } from '@/api/usercenter'

export default {
  data() {
    const validateNewPassword = (rule, value, callback) => {
      if (this.createPlateformUserForm.newPssword !== '' && this.createPlateformUserForm.confirmNewPssword !== '' && this.createPlateformUserForm.newPssword !== this.createPlateformUserForm.confirmNewPssword) {
        callback(new Error('密码不一致，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      selCluster: '',
      clusterOptions: [],
      searchText: '',
      // 总页数
      totalPage: 0,
      // 每页条数
      pageSize: 20,
      // 当前页
      pageNumber: 1,
      dialog: {
        createUser: false,
        editUser: false
      },
      createPlateformUserForm: {
        email: '',
        userName: '',
        password: '',
        confirmNewPssword: '',
        newPssword: ''
      },
      rulesCreateUser: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmNewPssword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '请输入6位以上的密码' },
          { validator: validateNewPassword }
        ],
        newPssword: [
          { required: true, message: '请重复输入新密码', trigger: 'blur' },
          { min: 6, message: '请输入6位以上的密码' },
          { validator: validateNewPassword }
        ]
      }
    }
  },
  created() {
    this._handleUser('Get')
  },
  methods: {
    // 搜索
    doSearch(searchAll) {
      if (searchAll) {
        this._handleUser('Get')
      } else {
        this._handleUser('Get', '', this.searchText)
      }
    },
    // 点击table名称
    toDetail(row) {
      this.$store.dispatch('SaveCurCLuster', row)
      this.$router.push({ path: '/cluster/nodes' })
    },
    // 停止任务
    stopTask(row) {
      this.$confirm('此操作将停止该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._taskOperation(this.selCluster, row.name)
      })
    },
    // 修改用户
    clickModifyUser(row) {
      this.dialog.createUser = true
      this.dialog.editUser = true
      this.createPlateformUserForm.email = row.email
      this.createPlateformUserForm.userName = row.userName
    },
    // 表单提交(createPlateformUserForm: 新建用户)
    submitForm() {
      const method = this.dialog.editUser ? 'Put' : 'Post'
      this.$refs['createPlateformUserForm'].validate((valid) => {
        if (valid) {
          let data = {}
          if (!this.dialog.editUser) {
            data = {
              email: this.createPlateformUserForm.email,
              userName: this.createPlateformUserForm.userName,
              password: this.createPlateformUserForm.password
            }
          } else {
            data = {
              email: this.createPlateformUserForm.email,
              password: this.createPlateformUserForm.newPssword,
              anotherPassword: this.createPlateformUserForm.confirmNewPssword
            }
          }
          this._handleUser(method, data)
          this.dialog.createSource = false
          this.resetForm('createPlateformUserForm')
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.dialog.editUser = false
      this.dialog.createUser = false
      this.createSourceForm = {
        email: '',
        userName: '',
        password: '',
        confirmNewPssword: '',
        newPssword: ''
      }
      this.$refs[formName].resetFields()
    },
    // 用户操作（查询列表：Get,新增：Post,修改：Put,删除：Delete）
    _handleUser(method, data, query) {
      this.listLoading = true
      const searchQuery = query ? `?email=${query}` : ''
      handlePlateFormUser(method, data, searchQuery).then(res => {
        if (res.message.code === 0) {
          this.listLoading = false
          switch (method) {
            case 'Get':
              this.list = res.data
              break
            case 'Post':
              this.$message({ message: '新建成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
            case 'Put':
              this.$message({ message: '修改成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
            case 'Delete':
              this.$message({ message: '删除成功', showClose: true, type: 'success' })
              this._handleUser('Get')
              break
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.usercenter {
  &-header {
    padding: 10px;
    background: #ffffff;
    font-size: 14px;
    color: #303133;
    font-weight: bold;
    .header-title {
      font-size: 14px;
      font-weight: 700;
    }
    .search-box {
      float: right;
    }
    .el-input__inner {
      height: 28px;
    }
  }
  label {
    font-weight: normal
  }
  .table-action {
    color: #4285f4;
  }
  .table-link {
    &:hover {
      color: #4285f4;
    }
  }
}
</style>
